const mysql = require('mysql2/promise');

async function testConnection() {
  try {
    console.log('Testing database connection...');
    
    const connection = await mysql.createConnection({
      host: '47.92.153.176',
      port: 3306,
      user: 'root',
      password: 'Hld20020729@',
      database: 'KeHuBaiFangDatabase'
    });

    console.log('✅ Database connection successful!');
    
    // Test if database exists
    const [databases] = await connection.execute('SHOW DATABASES');
    console.log('Available databases:', databases.map(db => db.Database));
    
    // Check if our database exists
    const dbExists = databases.some(db => db.Database === 'KeHuBaiFangDatabase');
    if (dbExists) {
      console.log('✅ Database "KeHuBaiFangDatabase" exists');
    } else {
      console.log('❌ Database "KeHuBaiFangDatabase" does not exist');
      console.log('Creating database...');
      await connection.execute('CREATE DATABASE IF NOT EXISTS KeHuBaiFangDatabase');
      console.log('✅ Database created successfully');
    }
    
    await connection.end();
  } catch (error) {
    console.error('❌ Database connection failed:', error.message);
    console.error('Error code:', error.code);
    
    if (error.code === 'ER_ACCESS_DENIED_ERROR') {
      console.log('Please check your username and password');
    } else if (error.code === 'ECONNREFUSED') {
      console.log('Please check if MySQL server is running and accessible');
    } else if (error.code === 'ER_BAD_DB_ERROR') {
      console.log('Database does not exist, will try to create it');
    }
  }
}

testConnection();
